/*
 * @Author: zhaiyujia
 * @Date: 2022-11-16 00:43:31
 * @LastEditors: zhaiyujia
 * @LastEditTime: 2022-11-17 15:01:00
 * @Description: ProtoThreads Sem test.
 */

#include "Arduino.h"

#define PT_USE_SEM
#define PT_USE_TIMER
#include "pt/pt.h"

static struct pt pt1, pt2;
static struct pt_sem sem_LED;

#define LED D55
#define KEY D54

static int protothread1(struct pt *pt)
{
    PT_BEGIN(pt);
    while (1)
    {
        PT_SEM_WAIT(pt, &sem_LED);
        digitalWrite(LED, !digitalRead(LED));
        PT_TIMER_DELAY(pt, 1000); // delay(1000);
        PT_SEM_SIGNAL(pt, &sem_LED);
        PT_YIELD(pt);
    }
    PT_END(pt);
}

unsigned char i;
static int protothread2(struct pt *pt)
{
    PT_BEGIN(pt);
    while (1)
    {
        PT_WAIT_UNTIL(pt, !digitalRead(KEY));
        PT_SEM_WAIT(pt, &sem_LED);
        for (i = 0; i < 5; i++)
        {
            digitalWrite(LED, HIGH);
            PT_TIMER_DELAY(pt, 200); // delay(200);
            digitalWrite(LED, LOW);
            PT_TIMER_DELAY(pt, 200); // delay(200);
        }
        PT_SEM_SIGNAL(pt, &sem_LED);
    }
    PT_END(pt);
}

void setup()
{
    pinMode(LED, OUTPUT);
    pinMode(KEY, INPUT);
    Serial_begin(115200);
    Serial_println("Hello Arduino-STC.");
    PT_SEM_INIT(&sem_LED, 1);
    PT_INIT(&pt1);
    PT_INIT(&pt2);
}
void loop()
{
    protothread1(&pt1);
    protothread2(&pt2);
}